package com.xysd.express.activity.expressage;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.xysd.express.R;
import com.xysd.express.activity.logistics.SelectCompanyActivity;
import com.xysd.express.activity.logistics.ShipmentsActivity;
import com.xysd.express.base.BaseActivity;
import com.xysd.express.bean.CargoTypeBus;
import com.xysd.express.bean.CompanyListObj;
import com.xysd.express.eventbus.LogisticsSendInfoEvent;
import com.xysd.express.rx.RxBus;
import com.xysd.express.util.ActivityTaskManeger;
import com.xysd.express.util.GlideImageLoader;
import com.xysd.express.util.JSONParser;
import com.xysd.express.util.ToastUtil;
import com.xysd.express.util.http.HttpCallBack;
import com.xysd.express.util.http.HttpUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import rx.Subscription;
import rx.functions.Action1;

@ContentView(R.layout.activity_expressage)
public class ExpressageActivity extends BaseActivity implements View.OnClickListener {

    @ViewInject(R.id.banner)
    private Banner banner;
    @ViewInject(R.id.send_layout)
    private LinearLayout send_layout;
    @ViewInject(R.id.adds_send_tv)
    private TextView adds_send_tv;
    @ViewInject(R.id.name_tel_send_tv)
    private TextView name_tel_send_tv;
    @ViewInject(R.id.company_tv)
    private TextView company_tv;
    @ViewInject(R.id.cargoType_tv)
    private TextView cargoType_tv;
    @ViewInject(R.id.weight_et)
    private TextView weight_et;
    @ViewInject(R.id.time_tv)
    private TextView time_tv;
    @ViewInject(R.id.comfirm_btn)
    private Button comfirm_btn;

    private String weight;
    Subscription rxSbscription_send;//回调选择地址的RxBus
    Subscription rxSbscription_cargotype;//回调选择物品类型的RxBus

    String company,companyId,adds,adds_details,name,tel,time,remark;
    int cargotypeId;
    String cargoName;

    private List<String> bannerUrls=new ArrayList<>();

    @Override
    protected void init() {
        setTitleBar("快递");
        getdata();
        send_layout.setOnClickListener(this);
        company_tv.setOnClickListener(this);
        cargoType_tv.setOnClickListener(this);
        time_tv.setOnClickListener(this);
        comfirm_btn.setOnClickListener(this);
        weight_et.setOnClickListener(this);
        initRxBus();
    }

    private void initRxBus() {

        rxSbscription_send= RxBus.getInstance().toObserverable(LogisticsSendInfoEvent.class)
                .subscribe(new Action1<LogisticsSendInfoEvent>() {
                    @Override
                    public void call(LogisticsSendInfoEvent event) {
                        Log.i("RxBus_send",event.toString());
                        adds_send_tv.setText(event.adds);
                        name_tel_send_tv.setText(event.name+"  "+event.tel);
                        adds=event.adds;
                        adds_details=event.adds_details;
                        name=event.name;
                        tel=event.tel;
                    }
                });

        rxSbscription_cargotype= RxBus.getInstance().toObserverable(CargoTypeBus.class)
                .subscribe(new Action1<CargoTypeBus>() {
                    @Override
                    public void call(CargoTypeBus event) {
                        Log.i("RxBus_cargotype",event.toString());
                        cargotypeId=event.Id;
                        cargoName=event.Name;
                        remark=event.Remark;
                        cargoType_tv.setText(cargoName);
                    }
                });
    }

    private void getdata() {
        HttpUtil.getExpressageBanner(new HttpCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.i("快递banner",result);
                String code = JSONParser.getStringFromJsonString("Status",result);
                String msg = JSONParser.getStringFromJsonString("Msg",result);
                if ("0".equals(code)){
                    String data = JSONParser.getStringFromJsonString("Data",result);
                    bannerUrls=JSONParser.JSON2Array(data,String.class);
                    initBanner(bannerUrls);
                }else {
                    ToastUtil.show(msg);
                }
            }

            @Override
            public void onFailure(String error) {
                Log.e("快递banner",error);
            }
        });
    }

    private void initBanner(List<String> imgUrls) {
        //https://github.com/youth5201314/banner 教程地址
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(imgUrls);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
//        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(2500);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    //时间选择器
    private void showTimePicker(final TextView timeView) {
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String timeStr = sdf.format(date);
                timeView.setText(timeStr);
            }
        })
                .setTitleText("选择时间")//标题文字
                .isCyclic(false)//是否循环滚动
                .setType(new boolean[]{true, true, true, true, true, true})// 默认全部显示
                .setLabel("年", "月", "日", "时", "分", "秒")
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCompanySelectEvent(CompanyListObj.Company event){
        companyId=event.CommpanyId+"";
        company_tv.setText(event.CompanyName);
        company=event.CompanyName;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.send_layout:
                startAty(ShipmentsActivity.class);
                break;
            case R.id.company_tv:
                Intent companyintent=new Intent(mActivity,SelectCompanyActivity.class);
                companyintent.putExtra("from",222);
                startActivity(companyintent);
                break;
            case R.id.cargoType_tv:
                startAty(SelecteExpressageTypeActivity.class);
                break;
            case R.id.time_tv:
                showTimePicker(time_tv);
                break;
            case R.id.comfirm_btn:
                time=time_tv.getText().toString();
                weight=weight_et.getText().toString();
                publish();
                break;
            case R.id.weight_et:
                break;
        }
    }

    private void publish() {
        if (TextUtils.isEmpty(adds)){
            ToastUtil.show("您还未选择发件人信息");
            return;
        }
        if (TextUtils.isEmpty(company)){
            ToastUtil.show("您还未选择快递公司");
            return;
        }
        if (TextUtils.isEmpty(weight)){
            ToastUtil.show("您还填写物品重量");
            return;
        }
        if (TextUtils.isEmpty(time)){
            ToastUtil.show("您还未选择取件时间");
            return;
        }

        HttpUtil.publishExpressage(companyId, adds, adds_details, name, tel, cargotypeId, cargoName, weight, time, remark, new HttpCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.i("发布快递",result);
                String code =JSONParser.getStringFromJsonString("Status",result);
                String msg =JSONParser.getStringFromJsonString("Msg",result);
                if ("0".equals(code)){
                    ActivityTaskManeger.getInstance().closeActivity(mActivity);
                }else {
                    ToastUtil.show(msg);
                }

            }

            @Override
            public void onFailure(String error) {
                Log.e("发布快递",error);
            }
        });

    }
}
